{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import OnePy as op\n",
    "from OnePy.custom_module.cleaner_talib import Talib\n",
    "\n",
    "\n",
    "class TalibStrategy(op.StrategyBase):\n",
    "\n",
    "    def __init__(self):\n",
    "\n",
    "        super().__init__()\n",
    "\n",
    "        self.sma1 = Talib(ind='sma',\n",
    "                          params=dict(timeperiod=2), buffer_day=30).calculate\n",
    "        self.sma2 = Talib(ind='sma',\n",
    "                          params=dict(timeperiod=3), buffer_day=40).calculate\n",
    "        \n",
    "        # 参数优化必须将参数以字典形式存入params中\n",
    "        self.params = dict(     \n",
    "            position=100,\n",
    "            takeprofit=10,\n",
    "            stoploss=10,\n",
    "            sma1=5,\n",
    "            sma2=20,\n",
    "        )\n",
    "\n",
    "    def set_params(self, params: dict):\n",
    "        \"\"\"\n",
    "        该函数主要用于参数优化，配置好cleaner\n",
    "        \"\"\"\n",
    "        self.params.update(params) # 第一行必须运行这个update函数\n",
    "        \n",
    "        self.sma1 = Talib(ind='sma',\n",
    "                          params=dict(timeperiod=params['sma1']),\n",
    "                          buffer_day=30).calculate\n",
    "        self.sma2 = Talib(ind='sma',\n",
    "                          params=dict(timeperiod=params['sma2']),\n",
    "                          buffer_day=40).calculate\n",
    "\n",
    "    def handle_bar(self):\n",
    "\n",
    "        position = self.params['position']\n",
    "        takeprofit = self.params['takeprofit']\n",
    "        stoploss = self.params['position']\n",
    "\n",
    "        for ticker in self.env.tickers:\n",
    "\n",
    "            if self.sma1(ticker) > self.sma2(ticker):\n",
    "                self.buy(position, ticker,\n",
    "                         takeprofit=takeprofit, stoploss=stoploss)\n",
    "            else:\n",
    "                self.sell(position, ticker)\n",
    "\n",
    "\n",
    "TICKER_LIST = ['000001']\n",
    "INITIAL_CASH = 20000\n",
    "FREQUENCY = 'D'\n",
    "START, END = '2017-05-25', '2017-07-09'\n",
    "\n",
    "TalibStrategy()\n",
    "\n",
    "go = op.backtest.stock(TICKER_LIST, FREQUENCY, INITIAL_CASH, START, END)\n",
    "# go.sunny() # 注意，参数优化optimizer之前不能运行go.sunny(), 不然会报错"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "一共优化 5 次\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "正在初始化OnePy\n",
      "正在初始化OnePy\n",
      "正在初始化OnePy\n",
      "正在初始化OnePy\n",
      "正在初始化OnePy\n",
      "=============== OnePy初始化成功！ ===============\n",
      "=============== OnePy初始化成功！ ===============\n",
      "=============== OnePy初始化成功！ ===============\n",
      "开始寻找OnePiece之旅~~~\n",
      "开始寻找OnePiece之旅~~~\n",
      "开始寻找OnePiece之旅~~~\n",
      "=============== OnePy初始化成功！ ===============\n",
      "=============== OnePy初始化成功！ ===============\n",
      "开始寻找OnePiece之旅~~~\n",
      "开始寻找OnePiece之旅~~~\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前是第 1 次, 剩余 0.00 mins\n",
      "当前是第 2 次, 剩余 0.00 mins\n",
      "当前是第 3 次, 剩余 0.00 mins\n",
      "当前是第 4 次, 剩余 0.00 mins\n",
      "当前是第 5 次, 剩余 0.00 mins\n",
      "参数优化完成!\n"
     ]
    }
   ],
   "source": [
    "go.optimizer.set_params(strategy_name=\"TalibStrategy\", \n",
    "                        param='takeprofit', \n",
    "                        param_range=[10])\n",
    "\n",
    "go.optimizer.set_params(\"TalibStrategy\", 'stoploss', [10])\n",
    "go.optimizer.set_params(\"TalibStrategy\", 'position', [100])\n",
    "go.optimizer.set_params(\"TalibStrategy\", 'sma1', range(3, 8))\n",
    "go.optimizer.set_params(\"TalibStrategy\", 'sma2', [20])\n",
    "\n",
    "result = go.optimizer.run(filename='test.pkl')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'Start_date': '2017-05-25',\n",
       "  'End_date': '2017-07-09',\n",
       "  'Initial_balance': '$20000.00',\n",
       "  'End_balance': '$20174.61',\n",
       "  'Total_return': '0.87%',\n",
       "  'Total_net_pnl': '$174.61',\n",
       "  'Total_commission': '$41.39',\n",
       "  'Total_trading_days': '33 days',\n",
       "  'Max_drawdown': '0.38%',\n",
       "  'Max_drawdown_date': '2017-06-19',\n",
       "  'Max_duration_in_drawdown': '7 days',\n",
       "  'Max_margin': '$0.00',\n",
       "  'Max_win_holding_pnl': '$55.36',\n",
       "  'Max_loss_holding_pnl': '-$56.50',\n",
       "  'Sharpe_ratio': '3.27',\n",
       "  'Sortino_ratio': '6.69',\n",
       "  'Number_of_trades': '29',\n",
       "  'Number_of_daily_trades': '0.88',\n",
       "  'Number_of_profit_days': '33 days',\n",
       "  'Number_of_loss_days': '0 days',\n",
       "  'Avg_daily_pnl': '$5.29',\n",
       "  'Avg_daily_commission': '$1.25',\n",
       "  'Avg_daily_return': '0.03%',\n",
       "  'Avg_daily_std': '0.03%',\n",
       "  'Annual_compound_return': '7.09%',\n",
       "  'Annual_average_return': '6.85%',\n",
       "  'Annual_std': '0.43%',\n",
       "  'Annual_pnl': '$1333.41',\n",
       "  'TalibStrategy': {'takeprofit': 10,\n",
       "   'stoploss': 10,\n",
       "   'position': 100,\n",
       "   'sma1': 3,\n",
       "   'sma2': 20}},\n",
       " {'Start_date': '2017-05-25',\n",
       "  'End_date': '2017-07-09',\n",
       "  'Initial_balance': '$20000.00',\n",
       "  'End_balance': '$20174.61',\n",
       "  'Total_return': '0.87%',\n",
       "  'Total_net_pnl': '$174.61',\n",
       "  'Total_commission': '$41.39',\n",
       "  'Total_trading_days': '33 days',\n",
       "  'Max_drawdown': '0.38%',\n",
       "  'Max_drawdown_date': '2017-06-19',\n",
       "  'Max_duration_in_drawdown': '7 days',\n",
       "  'Max_margin': '$0.00',\n",
       "  'Max_win_holding_pnl': '$55.36',\n",
       "  'Max_loss_holding_pnl': '-$56.50',\n",
       "  'Sharpe_ratio': '3.27',\n",
       "  'Sortino_ratio': '6.69',\n",
       "  'Number_of_trades': '29',\n",
       "  'Number_of_daily_trades': '0.88',\n",
       "  'Number_of_profit_days': '33 days',\n",
       "  'Number_of_loss_days': '0 days',\n",
       "  'Avg_daily_pnl': '$5.29',\n",
       "  'Avg_daily_commission': '$1.25',\n",
       "  'Avg_daily_return': '0.03%',\n",
       "  'Avg_daily_std': '0.03%',\n",
       "  'Annual_compound_return': '7.09%',\n",
       "  'Annual_average_return': '6.85%',\n",
       "  'Annual_std': '0.43%',\n",
       "  'Annual_pnl': '$1333.41',\n",
       "  'TalibStrategy': {'takeprofit': 10,\n",
       "   'stoploss': 10,\n",
       "   'position': 100,\n",
       "   'sma1': 6,\n",
       "   'sma2': 20}},\n",
       " {'Start_date': '2017-05-25',\n",
       "  'End_date': '2017-07-09',\n",
       "  'Initial_balance': '$20000.00',\n",
       "  'End_balance': '$20166.02',\n",
       "  'Total_return': '0.83%',\n",
       "  'Total_net_pnl': '$166.02',\n",
       "  'Total_commission': '$39.98',\n",
       "  'Total_trading_days': '33 days',\n",
       "  'Max_drawdown': '0.38%',\n",
       "  'Max_drawdown_date': '2017-06-19',\n",
       "  'Max_duration_in_drawdown': '7 days',\n",
       "  'Max_margin': '$0.00',\n",
       "  'Max_win_holding_pnl': '$55.36',\n",
       "  'Max_loss_holding_pnl': '-$56.50',\n",
       "  'Sharpe_ratio': '3.12',\n",
       "  'Sortino_ratio': '6.30',\n",
       "  'Number_of_trades': '28',\n",
       "  'Number_of_daily_trades': '0.85',\n",
       "  'Number_of_profit_days': '33 days',\n",
       "  'Number_of_loss_days': '0 days',\n",
       "  'Avg_daily_pnl': '$5.03',\n",
       "  'Avg_daily_commission': '$1.21',\n",
       "  'Avg_daily_return': '0.03%',\n",
       "  'Avg_daily_std': '0.03%',\n",
       "  'Annual_compound_return': '6.73%',\n",
       "  'Annual_average_return': '6.51%',\n",
       "  'Annual_std': '0.41%',\n",
       "  'Annual_pnl': '$1267.80',\n",
       "  'TalibStrategy': {'takeprofit': 10,\n",
       "   'stoploss': 10,\n",
       "   'position': 100,\n",
       "   'sma1': 7,\n",
       "   'sma2': 20}},\n",
       " {'Start_date': '2017-05-25',\n",
       "  'End_date': '2017-07-09',\n",
       "  'Initial_balance': '$20000.00',\n",
       "  'End_balance': '$20174.61',\n",
       "  'Total_return': '0.87%',\n",
       "  'Total_net_pnl': '$174.61',\n",
       "  'Total_commission': '$41.39',\n",
       "  'Total_trading_days': '33 days',\n",
       "  'Max_drawdown': '0.38%',\n",
       "  'Max_drawdown_date': '2017-06-19',\n",
       "  'Max_duration_in_drawdown': '7 days',\n",
       "  'Max_margin': '$0.00',\n",
       "  'Max_win_holding_pnl': '$55.36',\n",
       "  'Max_loss_holding_pnl': '-$56.50',\n",
       "  'Sharpe_ratio': '3.27',\n",
       "  'Sortino_ratio': '6.69',\n",
       "  'Number_of_trades': '29',\n",
       "  'Number_of_daily_trades': '0.88',\n",
       "  'Number_of_profit_days': '33 days',\n",
       "  'Number_of_loss_days': '0 days',\n",
       "  'Avg_daily_pnl': '$5.29',\n",
       "  'Avg_daily_commission': '$1.25',\n",
       "  'Avg_daily_return': '0.03%',\n",
       "  'Avg_daily_std': '0.03%',\n",
       "  'Annual_compound_return': '7.09%',\n",
       "  'Annual_average_return': '6.85%',\n",
       "  'Annual_std': '0.43%',\n",
       "  'Annual_pnl': '$1333.41',\n",
       "  'TalibStrategy': {'takeprofit': 10,\n",
       "   'stoploss': 10,\n",
       "   'position': 100,\n",
       "   'sma1': 4,\n",
       "   'sma2': 20}},\n",
       " {'Start_date': '2017-05-25',\n",
       "  'End_date': '2017-07-09',\n",
       "  'Initial_balance': '$20000.00',\n",
       "  'End_balance': '$20174.61',\n",
       "  'Total_return': '0.87%',\n",
       "  'Total_net_pnl': '$174.61',\n",
       "  'Total_commission': '$41.39',\n",
       "  'Total_trading_days': '33 days',\n",
       "  'Max_drawdown': '0.38%',\n",
       "  'Max_drawdown_date': '2017-06-19',\n",
       "  'Max_duration_in_drawdown': '7 days',\n",
       "  'Max_margin': '$0.00',\n",
       "  'Max_win_holding_pnl': '$55.36',\n",
       "  'Max_loss_holding_pnl': '-$56.50',\n",
       "  'Sharpe_ratio': '3.27',\n",
       "  'Sortino_ratio': '6.69',\n",
       "  'Number_of_trades': '29',\n",
       "  'Number_of_daily_trades': '0.88',\n",
       "  'Number_of_profit_days': '33 days',\n",
       "  'Number_of_loss_days': '0 days',\n",
       "  'Avg_daily_pnl': '$5.29',\n",
       "  'Avg_daily_commission': '$1.25',\n",
       "  'Avg_daily_return': '0.03%',\n",
       "  'Avg_daily_std': '0.03%',\n",
       "  'Annual_compound_return': '7.09%',\n",
       "  'Annual_average_return': '6.85%',\n",
       "  'Annual_std': '0.43%',\n",
       "  'Annual_pnl': '$1333.41',\n",
       "  'TalibStrategy': {'takeprofit': 10,\n",
       "   'stoploss': 10,\n",
       "   'position': 100,\n",
       "   'sma1': 5,\n",
       "   'sma2': 20}}]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
